<?php

namespace Biz\service\SuperSubsidy;

use Biz\model\SuperSubsidy\YouZanBrandUserModel;

class YouZanBrand implements ConstInterface
{
    const ENCRYT_KEY = '@xNn9xw5%UdpyZ2i';

    public static function getAccountByToken($token)
    {
        $info = YouZanBrandUserModel::getByWhere(['token' => $token], ['id', 'brand_name', 'account_name', 'token', 'token_expired']);
        if ($info && $info['token_expired'] > time()) {
            return $info;
        }
        return false;
    }

    public static function Login($accountName, $accountPassword)
    {
        $info = YouZanBrandUserModel::getByWhere(['account_name' => $accountName]);
        if (empty($info)) {
            throw new \Exception('不存在的账户');
        }
        $infoPassword = self::decryptData($info['account_password']);
        $password = md5($accountName . $infoPassword);
        if ($password == $accountPassword) {
            $token = self::createToken();
            $tokenExpired = time() + 86400;
            $res = YouZanBrandUserModel::updateData(['token' => $token, 'token_expired' => $tokenExpired], ['id' => $info['id']]);
            return [
                'id' => $info['id'],
                'account_name' => $info['account_name'],
                'brand_name' => $info['brand_name'],
                'token' => $token
            ];
        }
        return false;
    }

    public static function LogOut($token)
    {
        YouZanBrandUserModel::updateData(['token' => 'logout_' . $token, 'token_expired' => 0], ['token' => $token]);
    }

    public static function createUserAccount($brandName, $adminId = 0)
    {
        $res = true;
        $userInfo = YouZanBrandUserModel::getByWhere(['brand_name' => $brandName]);
        if (empty($userInfo)) {
            $data = [
                'brand_name' => $brandName,
                'account_name' => self::genName(),
                'account_password' => self::genPassword(),
                'admin_id' => $adminId,
                'token' => self::createToken()
            ];
            $res = YouZanBrandUserModel::insertData($data);
        }
        return $res;
    }

    private static function createToken()
    {
        $token = md5(str_shuffle(microtime()));
        $info = YouZanBrandUserModel::getByWhere(['token' => $token]);
        if (!empty($info)) {
            return self::createToken();
        }
        return $token;

    }

    private static function genName()
    {
        $rand = sprintf("%04d", mt_rand(0, 999));
        $time_tail = substr(time(), -4);
        $accountName = 'subsidy-' . $time_tail . $rand;
        $userInfo = YouZanBrandUserModel::getByWhere(['account_name' => $accountName]);
        if (!empty($userInfo)) {
            return self::genName();
        }
        return $accountName;
    }

    private static function genPassword($length = 10)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&*-_';
        $password = '';
        for ($i = 0; $i < $length; $i++) {
            $password .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        $password = self::encryptData($password);
        return $password;
    }

    public static function encryptData($str)
    {
        $encryptHash = hash_pbkdf2("sha256", self::ENCRYT_KEY, self::ENCRYT_KEY, 1000, 32, true);
        $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length("aes-256-cbc"));
        $encrypted = openssl_encrypt($str, "aes-256-cbc", $encryptHash, 0, $iv);
        $encrypted = base64_encode($encrypted . ":" . bin2hex($iv));
        return $encrypted;
    }

    public static function decryptData($data)
    {
        $encryptHash = hash_pbkdf2("sha256", self::ENCRYT_KEY, self::ENCRYT_KEY, 1000, 32, true);
        list($encrypted_data, $iv) = explode(':', base64_decode($data), 2);
        return openssl_decrypt($encrypted_data, 'aes-256-cbc', $encryptHash, 0, hex2bin($iv));
    }
}